import os, sys, re, codecs
from pyexpat.errors import codes
import json
from collections import OrderedDict
import numpy as np

frame_shift = 0.01
frame_size = 0.25

class Jsonunit(object):
    """Storing word's start end 

    Args:
        object (_type_): _description_
    """
    def __init__(self, word, start, end):
        self.word = word
        self.start = start
        self.end = end
    
    def __str__(self) -> str:
        pass

    def get_endpoint(self) ->[float, float]:
        # comment: 
        return [float(self.start), float(self.end)]

    def get_word(self) ->str:
        # comment: 
        return self.word
    # end def


def timeseq2lables(sent_name, time_seq, total_time) -> (str, list):
    # comment: 
    if sent_name == "" or not isinstance(time_seq, list) or len(time_seq) == 0:
        return (sent_name, [])
    for i in range(len(time_seq)):


# end def

def read_utt2dur(arg4utt2dur):
    # comment: 
    if not os.path.exists(arg4utt2dur):
        raise FileNotFoundError
    
    dur_info = OrderedDict()
    with codes.open(arg4utt2dur, "r") as f:
        sent_line = f.readline().strip()
        while sent_line:
            sent_id, dur = re.split(r"\s+", sent_line)
            dur_info[sent_id] = float(dur)
            sent_line = f.readline().strip()
# end def


def main(ctm_file_name, utt2dur_fn, dst_dir):
    if (not os.path.exists(ctm_file_name)):
        # comment: 
        raise Exception("File not exits\n")
    
    dur_info = read_utt2dur(utt2dur_fn)
    time_info = OrderedDict()
    with open(ctm_file_name, "r") as f:
        prev_file_id = ''
        line = f.readline().strip("\n")
        unk_found = False
        while line:
            line_units = re.split(r"\s+", line)
            if len(line_units) != 5:
                continue
            if line_units[4] == "<UNK>":
                line = f.readline().strip("\n")
                unk_found = True
                continue
            if prev_file_id == "":
                prev_file_id = line_units[0]
                time_info[prev_file_id] = []
                time_info[prev_file_id].append(Jsonunit(line_units[4], float(line_units[2]), float(line_units[3])))
            else:
                if (prev_file_id != line_units[0]):
                    # comment: New sentence start
                    if unk_found:
                        del time_info[prev_file_id]
                        unk_found = False
                    prev_file_id = line_units[0]
                    time_info[prev_file_id] = []
                    time_info[prev_file_id].append(Jsonunit(line_units[4], float(line_units[2]), float(line_units[3])))
                else:
                    # comment: continue this sentence
                    time_info[prev_file_id].append(Jsonunit(line_units[4], float(line_units[2]), float(line_units[3])))
            
            line = f.readline().strip("\n")

                # end if
    # end if
    # assert len(dur_info) == len(time_info)
    if not os.path.exists(dst_dir):
        os.mkdir(dst_dir)
    for key, value in time_info.items():
        # comment: 
        timeseq2lables(key, value, total_time=dur_info[key])
        
    # end for


if __name__ == "__main__":
    if len(sys.argv) == 4:
        ctm_file_name = sys.argv[1]
        utt2dur = sys.argv[2]
        label_dir = sys.argv[3]
        main(ctm_file_name=ctm_file_name, utt2dur_fn=utt2dur, label_dir=label_dir)
    else:
        sys.stdout.write("{} {} {}\n".format(sys.argv[0], "ctm", "label_dir"))
        raise Exception("Parameter is not enough")
